package com.fashion.schedule;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Date: 1/22/13
 * Time: 10:26 AM
 */
@Service("pictureDownloader")
public class PictureDownloader {
   private static Logger logger = Logger.getLogger(PictureDownloader.class.getName()) ;

    public boolean saveUrlAs(String fileUrl, String savePath)
    {
        try {
            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            DataInputStream in = new DataInputStream(connection.getInputStream());
            DataOutputStream out = new DataOutputStream(new FileOutputStream(savePath));
            byte[] buffer = new byte[4096];
            int count = 0;
            while ((count = in.read(buffer)) > 0)
            {
                out.write(buffer, 0, count);
            }

            out.close();
            in.close();
            connection.disconnect();

            return true;
        } catch (Exception e) {
            logger.error("Failed to download picture: " + fileUrl + " to local: " + savePath);
            return false;
        }
    }

    public static void main(String[] args) {
        PictureDownloader pic = new PictureDownloader();

        String photoUrl = "http://1.bp.blogspot.com/-2YfI5-YnXFE/T-CaBF1xIcI/AAAAAAAAWA8/NTvBz3cYIV0/s1600/163.png";
        String fileName = photoUrl.substring(photoUrl.lastIndexOf("/"));
        String filePath = "C:\\Users\\yangk10\\Downloads";

        String savedFileName = filePath + fileName;
        if(pic.saveUrlAs(photoUrl, filePath + fileName)){
            logger.info("Just a test");
            logger.error("Run ok!\n Get URL file: " + photoUrl + " and save it to: " + savedFileName);
        } else {
            logger.error("Failed to download file: " + photoUrl);
        }
    }
}
